-- @name 承包地图自动化模块
-- @version 1.0.0
-- @description 承包地图状态监测与自动传送系统
-- @require modules/inventory.lua
-- @require modules/shop.lua
-- @require modules/movement.lua
-- @require modules/combat.lua

local ConfigLoader = require("config.loader")
local Settings = require("config.settings")
local config = ConfigLoader.load(Settings.CURRENT_GAME)
local logger = require "utils.logger"
local stateManager = require "utils.state_manager"
local inventory = require "modules.inventory"
local shop = require "modules.shop"
local movement = require "modules.movement"
local combat = require "modules.combat"
local tslib = require "TSLib"


local function main()
    logger.info("运行进入承包地图脚本")
    while true do
        local success, err = pcall(function()
            if not movement.isContractMap() then
                movement.useTownStone()
                movement.dragDirection('southwest', 2000)
                mSleep(1000)
              

                local attempts = 0
                local max_attempts = config.COLOR_MATCH.ATTEMPTS or 3
                while attempts < max_attempts do
                    -- local x,y = findMultiColorInRegionFuzzy(0xa09c9f, "7|17|0x383d5a,5|29|0x9c6a39,1|41|0x00ab00,32|23|0x6a6c7d", 95, 380, 210, 1428, 635, { orient = 2,max_miss = 3 })
                    local x,y = findMultiColorInRegionFuzzy(0x009a00, "4|0|0x00a000,10|-1|0x008200,17|-5|0x00db00,58|-3|0x00a100,59|-3|0x00a100", 90, 361, 319, 1226, 630, { orient = 2,main=0x202020,list=0x202020 })
                    if x ~= -1 then
                        logger.info(string.format("第%d次比色成功", attempts+1))
                        logger.info(string.format("坐标为:%d,%d", x, y))
                        movement.click(x, y)
                        movement.click(310,627)
                        if movement.isContractMap() then
                            logger.info("已到达承包地图")
                            combat.startAutoAttack()
                            break
                        else
                            movement.useTownStone()
                            movement.dragDirection('southwest', 1500)
                            mSleep(1000)
                        end
                    else
                        attempts = attempts + 1
                        logger.info(string.format("比色失败，已尝试%d次", attempts))
                        mSleep(config.COLOR_MATCH.RETRY_INTERVAL or 1000)
                    end
                end
            else
                logger.info("当前已在承包地图中")
            end
        end)
        if not success then
            logger.error("承包地图任务执行出错: " .. tostring(err))
            logger.error("错误堆栈: " .. debug.traceback())
        end
        
        -- 使用配置的检测间隔，默认为5分钟
        local checkInterval = config.CONTRACT_MAP.CHECK_INTERVAL or 300000
        logger.info("等待" .. checkInterval/1000 .. "秒后进行下一次检测")
        mSleep(checkInterval)
    end
end

return {
    run = main
}